import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/constants/index.dart';
import 'package:flutter_enjoy_plus/utils/PromptAction.dart';
import 'package:flutter_enjoy_plus/utils/RequestDio.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  String currentAddress = ""; // 当前地址
  List aroundList = []; //周边小区列表
  // 申请定位权限
  void _getPermission() async {
    if (kIsWeb) {
      _getCurrentAddress(116.350077, 40.065956);
      _getAroundAddress(116.350077, 40.065956);
      // PromptAction.showSuccess('40.065956,116.350077');
      // web端
      // (40.065956, 116.350077) 进行下一步
      // web端flutter有bug
    } else {
      // 鸿蒙端
      PermissionStatus status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        PromptAction.showSuccess("用户已授权地址位置权限");
        _getLocation();
      } else {
        PromptAction.showError("用户拒绝授权");
      }
    }
  }

  void _getLocation() async {
    try {
      Position res = await Geolocator.getCurrentPosition();
      // 鸿蒙端
      _getCurrentAddress(res.longitude, res.latitude);
      _getAroundAddress(res.longitude, res.latitude);
      // PromptAction.showSuccess('${res.latitude},${res.longitude}');
    } catch (e) {
      PromptAction.showError(e.toString());
    }
  }

  // 根据当前经纬度获取当前的位置-高德地图api-逆向地理解析
  void _getCurrentAddress(double longitude, double latitude) async {
    //  基础地址 如果你传了完整地址你的为准，没传以它的基础地址为准
    //requestDio.get(url)
    Dio dio = Dio();
    var res = await dio.get(GlobalVariable.GD_BASE + HTTP_PATH.REGEO,
        queryParameters: {
          "key": '7fa3641bc7047ff17930c47838b9c99e',
          "location": '$longitude,$latitude'
        });
    if (res.data["infocode"] == "10000") {
      currentAddress = res.data["regeocode"]["formatted_address"];
      setState(() {});
    } else {
      PromptAction.showError(res.data["info"]);
    }
  }

  void _getAroundAddress(double longitude, double latitude) async {
    //  基础地址 如果你传了完整地址你的为准，没传以它的基础地址为准
    //requestDio.get(url)
    Dio dio = Dio();
    var res = await dio
        .get(GlobalVariable.GD_BASE + HTTP_PATH.AROUND, queryParameters: {
      "key": '7fa3641bc7047ff17930c47838b9c99e',
      "location": '$longitude,$latitude',
      "keywords": "住宅小区",
      "radius": 500, // 搜索半径
      "offset": 10 // 就查10条
    });
    if (res.data["infocode"] == "10000") {
      aroundList = res.data["pois"];
      setState(() {});
    } else {
      PromptAction.showError(res.data["info"]);
    }
  }

  List<Widget> getChildren() {
    return aroundList.map((item) {
      return Container(
        color: Colors.white,
        padding: const EdgeInsets.all(10),
        child: GestureDetector(
          onTap: () {
            Navigator.pushNamed(context, "/building_list",
                arguments: {"point": item["name"]});
          },
          child: Row(
            children: [
              Expanded(child: Text(item['name'])),
              const Row(
                children: [
                  Icon(Icons.arrow_forward_ios, size: 16, color: Colors.black),
                ],
              )
            ],
          ),
        ),
      );
    }).toList();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 尝试去申请定位权限
    _getPermission(); // 申请定位权限
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const Row(
            children: [
              Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(currentAddress)),
                GestureDetector(
                  onTap: () {
                    _getAroundAddress(121.61158, 31.035041);
                    _getCurrentAddress(121.61158, 31.035041);
                  },
                  child: Row(
                    children: [
                      Icon(Icons.location_searching_outlined,
                          color: Colors.blue),
                      SizedBox(width: 2),
                      Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: getChildren(),
          )
        ],
      ),
    );
  }
}
